﻿
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using ZFY.Core;

namespace ZFY.Core
{
    public interface IZFYServiceProvider
    {
        T GetRequiredService<T>(Type type = null);
        T LazyGetRequiredService<T>();
    }

    public class ZFYServiceProvider : IZFYServiceProvider ,IScopeDependency
    {
        protected IDictionary<Type, object> CachedServices { get; set; }

        protected IServiceProvider ServiceProvider { get; set; }

        public ZFYServiceProvider(IServiceProvider serviceProvider)
        {
            ServiceProvider = serviceProvider;
            CachedServices = new Dictionary<Type, object>();
        }

        public virtual T LazyGetRequiredService<T>()
        {
            var type = typeof(T);

            CachedServices.TryGetValue(type, out object res);

            if (res is null)
            {
                var service = ServiceProvider.GetRequiredService<T>();

                CachedServices.Add(type, service);

                return service;
            }

            return (T)res;
        }

        public T GetRequiredService<T>(Type type = null)
        {
            type ??= typeof(T);

            if (typeof(IScopeDependency).IsAssignableFrom(type))
            {
                return ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext.RequestServices.GetRequiredService<T>();
            }

            return ServiceProvider.GetRequiredService<T>();
        }


    }

}
